package com.example.common.sdk.http

import com.google.gson.Gson
import com.google.gson.JsonElement
import com.google.gson.JsonParser
import com.google.gson.reflect.TypeToken
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.withContext

/**
 * 数据转换处理器
 */
object DataTransformProcessor {
    private val gson = Gson()

    /**
     * 只能转换 对象
     */
    suspend fun <R> transformObject(
        data: Any?,
        clazz: Class<R>? = null,
        typeToken: TypeToken<R>? = null
    ): R =
        withContext(Dispatchers.IO) {
            if (clazz != null) {
                val json = gson.toJson(data)
                return@withContext gson.fromJson(json, clazz)
            } else {
                val json = gson.toJson(data)
                return@withContext gson.fromJson(json, typeToken!!.type)
            }

        }

    /**
     * 只能转换 数组
     */
    suspend fun <R> transformArray(
        data: Any?,
        clazz: Class<R>? = null,
        typeToken: TypeToken<R>? = null
    ): List<R> =
        withContext(Dispatchers.IO) {
            if (clazz != null) {
                val json = gson.toJson(data)
                val parser = JsonParser.parseString(json).asJsonArray
                val list = mutableListOf<R>()
                for (element: JsonElement in parser) {
                    list.add(gson.fromJson(element, clazz))
                }
                return@withContext list
            } else {
                val json = gson.toJson(data)
                return@withContext gson.fromJson(json, typeToken!!.type)
            }

        }

    /**
     * 专门为gson 提供的方法 object 和 array 都能用
     */
    suspend fun <R> transformDataByType(
        data: Any,
        typeToken: TypeToken<R>
    ): R = withContext(Dispatchers.IO) {
        val json = gson.toJson(data)
        return@withContext gson.fromJson<R>(json, typeToken.type)
    }
}